#include "GameEngine/Moveable.hpp"

/**
 * Initialize a new movable object. Need to know the map to check collisions
 */
Moveable::Moveable(Map* p_map) : m_speed(0), m_map(p_map), m_height(0), m_width(0)
{
	this->m_lock 		= new sf::Mutex();
	this->m_position 	= new sf::Vector2f();

	this->m_position->x = 0;
	this->m_position->y = 0;
}

Moveable::~Moveable()
{
	delete this->m_lock;
	delete this->m_position;
}
/**
 * Set the new position if it safe of collision
 */
void Moveable::Setposition(sf::Vector2f p_newPosition)
{
	//Debug::printTrace(Debug::information, "GameEngine/GameEngine.Run Receipt X", Text::float2string(p_newPosition.x));
	//Debug::printTrace(Debug::information, "GameEngine/GameEngine.Run Receipt Y", Text::float2string(p_newPosition.y));

	m_lock->Lock();
		if(		this->m_map->GetTileFromPosition(p_newPosition.x			, p_newPosition.y) 				!= Map::Wall &&
				this->m_map->GetTileFromPosition(p_newPosition.x			, p_newPosition.y + m_height) 	!= Map::Wall &&
				this->m_map->GetTileFromPosition(p_newPosition.x + m_width	, p_newPosition.y) 				!= Map::Wall &&
				this->m_map->GetTileFromPosition(p_newPosition.x + m_width	, p_newPosition.y + m_height) 	!= Map::Wall)
		{
			if(p_newPosition.x <= DefaultValue::MAP_SIZE_X && p_newPosition.x >= 0)
				this->m_position->x = p_newPosition.x;
			if(p_newPosition.y <= DefaultValue::MAP_SIZE_Y && p_newPosition.y >= 0)
				this->m_position->y = p_newPosition.y;

			//Debug::printTrace(Debug::information, "GameEngine/Moveable.setPosition", Text::float2string(m_speed));
		}
		else
		{
			//Debug::printTrace(Debug::information, "GameEngine/Moveable.setPosition", "Player stopped");
		}
	m_lock->Unlock();
}
/**
 * return the actual position (copy)
 */
sf::Vector2f Moveable::Getposition()
{
	m_lock->Lock();
	sf::Vector2f l_position =  *(this->m_position);
	m_lock->Unlock();

	return l_position;
}
/**
 * return the speed of the object (copy)
 */
float Moveable::Getspeed()
{
	m_lock->Lock();
	float l_speed =  m_speed;
	m_lock->Unlock();

	return l_speed;
}

void Moveable::Setspeed(float p_val)
{
	m_lock->Lock();
	m_speed = p_val;
	m_lock->Unlock();
}
/**
 * return the Hitbox of the Object
 */
sf::FloatRect Moveable::GetHitBox()
{
	return sf::FloatRect(
			m_position->x,
			m_position->y,
			m_position->x + m_width,
			m_position->y + m_height);
}
